package com.oto.web.resource;

import java.io.StringReader;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.model.FlowDO;
import com.oto.model.PackDO;
import com.oto.util.JAXBUtils;
import com.oto.web.model.Message;
import com.oto.web.model.XmlAccount;
import com.oto.web.model.XmlFlow;
import com.oto.web.model.XmlPack;

/**
 * @author xueqiang.mi
 * @since 2010-12-19
 */
@Path("/mobile")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MobileResource extends BaseResource {

	@POST
	@Path("share")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String postShareForm(@FormParam(value = "data") String data) {
		if (StringUtils.isEmpty(data)) {
			return Constants.STATUS_ERROR + ": empty content.";
		}

		// log用户share的XML消息内容
		messageService.store(data);

		// 解析消息
		StringReader reader = new StringReader(data);
		Message msg = JAXBUtils.unmarshal(Constants.JAXB_CONTEXT_PATH, reader);

		// 处理消息
		XmlAccount from = msg.getFromUser();
		String userName = from == null ? Constants.DEFAULT_ANONYMOUS_USER : from.getName();

		List<XmlAccount> toList = msg.getToUsers();

		XmlPack xPack = msg.getPack();
		PackDO pack = packService.getOrCreate(xPack.getName(), userName);

		for (XmlFlow xFlow : xPack.getFlows()) {
			FlowDO f = new FlowDO();
			f.setName(xFlow.getName());
			f.setType(xFlow.getType());
			f.setContent(xFlow.getContent());
			f.setPackId(pack.getId());
			f.setOwner(userName);
			for (XmlAccount u : toList) {
				f.getUsers().add(u.getName());
			}
			flowService.add(f);

			// 将flow push给所有toList中的用户
			accountService.pushFlow(toList, f);
		}
		return Constants.STATUS_OK;
	}
}
